﻿using lwzlz.Application.System;
using lwzlz.Web.Areas.SysAdmin.Models;
using System;
using System.Web.Mvc;

namespace lwzlz.Web.Filter
{
    /// <summary>
    /// 菜单权限过滤器
    /// </summary>
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
    public class MenuFilterAttribute : ActionFilterAttribute
    {
        private readonly string _action;

        public MenuFilterAttribute() { }

        public MenuFilterAttribute(string action)
        {
            _action = action;
        }

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            // 验证权限
            CheckAuthority(filterContext);

            base.OnActionExecuting(filterContext);
        }

        /// <summary>
        /// 验证权限
        /// </summary>
        protected void CheckAuthority(ActionExecutingContext filterContext)
        {
            // 获取当前路由数据
            var route = filterContext.RouteData.Values;
            // 路由方法参数
            string action = route["action"].ToString();

            if (string.IsNullOrEmpty(_action))
            {
                // 获取自定义特性数组
                var attributes = filterContext.ActionDescriptor.GetCustomAttributes(true);
                if (attributes != null && attributes.Length > 0)
                {
                    foreach (var item in attributes)
                    {
                        var type = item.GetType();
                        if (type.Equals(typeof(NoFilterAttribute)))
                        {
                            return; // 有无需过滤特性则不验证
                        }
                        if (type.Equals(typeof(MenuRouteAttribute)))
                        {
                            action = ((MenuRouteAttribute)item).Action;
                        }
                    }
                }
            }
            else
            {
                action = _action;
            }

            // 待验证url
            var url = string.Format("/{0}/{1}/{2}", route["area"], route["controller"], action);
            var service = new AuthorityService();
            // 验证当前用户是否有此权限
            if (!service.CheckAuthority(url))
            {
                // 无权限
                string errorMsg = "你没有这项权限，请联系管理员！";
                // 设置返回值，不再执行action方法
                if (filterContext.RequestContext.HttpContext.Request.IsAjaxRequest())
                {
                    var result = new JsonResult();
                    result.Data = new ResponseModel()
                    {
                        Success = false,
                        Message = errorMsg
                    };

                    filterContext.Result = result;
                }
                else
                {
                    filterContext.Result = new ContentResult() { Content = errorMsg };
                }
            }
        }

    }
}